package cn.janyd.action.template;

import cn.janyd.action.Constants;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.io.StringWriter;

import static cn.janyd.action.Constants.UTF8;

/**
 * @author Janyd
 * @since 2020-08-09 1:21
 */
public class FreemarkerTemplateEngine implements TemplateEngine {


    private final Configuration configuration;

    public FreemarkerTemplateEngine() {
        configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setDefaultEncoding(UTF8);
        configuration.setClassForTemplateLoading(getClass(), Constants.SLASH);


    }

    /**
     * 生成代码
     *
     * @param codeTemplate 模板与元数据
     * @return 生成结果
     */
    @Override
    public byte[] generate(CodeTemplate codeTemplate) {
        StringWriter writer = new StringWriter();
        try {
            Template template = configuration.getTemplate(codeTemplate.getTemplatePath());
            template.process(codeTemplate.getObjectMap(), writer);
            return writer.toString().getBytes(UTF8);
        } catch (TemplateException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new byte[]{};
    }
}
